package thread.matrix.group;

import java.util.List;

public class ParalleGroupMultiplier {
    public static void multiply(double[][] matrix1,double[][] matrix2,double[][] result){
//        List<Thread> threads = new ArrayList<>();
        int cpuNum = Runtime.getRuntime().availableProcessors();
        int perCPU = matrix1.length%cpuNum==0 ? matrix1.length/cpuNum : matrix1.length/cpuNum+1;
        int start = 0;
        int end = start+perCPU;
        for (int i=0;i<cpuNum;i++){
            //每行一个线程，计算结果矩阵的值
            //创建线程
            Thread t = new Thread(new GroupMultiplierTask(matrix1,matrix2,result,start,end));
            t.start();
//            threads.add(t);
//            if (threads.size()%10==0){
//                waitForThread(threads);
//            }
            System.out.println("start:"+start+" end:"+end);
            start = end;
            //如果是最后一个线程，end为matrix1的行数
            if (i==cpuNum-1)
                end = matrix1.length;
            else
                end = start+perCPU;
        }
    }

    private static void waitForThread(List<Thread> threads) {
        for (Thread t:threads){
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
